<template>
  <a-form
      :model="ruleForm"
      v-bind="layout"
      :rules="rules"
      @finish="handleFinish"
  >
    <a-form-item label="样品名称" name="sample_name">
      <a-input v-model:value="ruleForm.sample_name" />
    </a-form-item>
    <a-form-item label="合金代码" name="alloy_code">
      <a-select
        v-model:value="ruleForm.alloy_code"
        style="width: 120px"
        ref="select"
      >
        <a-select-option
          v-for="item in alloyCodeSelectionOptions"
          :key="item.url"
        >
          {{ item.label }}
        </a-select-option>
      </a-select>
    </a-form-item>
    <a-form-item label="形态" name="sample_form">
      <a-input v-model:value="ruleForm.sample_form" />
    </a-form-item>
    <a-form-item label="形状" name="sample_shape">
      <a-input v-model:value="ruleForm.sample_shape" />
    </a-form-item>
    <a-form-item label="长" name="sample_length">
      <a-input v-model:value="ruleForm.sample_length" />
    </a-form-item>
    <a-form-item label="宽" name="sample_width">
      <a-input v-model:value="ruleForm.sample_width" />
    </a-form-item>
    <a-form-item label="厚度" name="sample_thickness">
      <a-input v-model:value="ruleForm.sample_thickness" />
    </a-form-item>
    <a-form-item label="直径" name="sample_diameter">
      <a-input v-model:value="ruleForm.sample_diameter" />
    </a-form-item>
    <a-form-item label="颜色" name="sample_col">
      <a-input v-model:value="ruleForm.sample_col" />
    </a-form-item>
    <a-form-item label="光泽度" name="sample_gloss">
      <a-input v-model:value="ruleForm.sample_gloss" />
    </a-form-item>
    <a-form-item label="粗糙度" name="sample_roughness">
      <a-input v-model:value="ruleForm.sample_roughness" />
    </a-form-item>

    <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
      <a-button type="primary" :loading="submitting" html-type="submit">
        {{ submitting ? '提交中' : '确定' }}
      </a-button>
    </a-form-item>
  </a-form>
</template>
<script>
import { message } from 'ant-design-vue'

export default {
  name: 'AddOrEditMacroOrganization',
  // url !== ''则为编辑操作，否则为添加
  props: ['url'],
  emits: ['operate-success', 'operate-failed'],

  data() {

    let isValidStr = (str) => {
      return str.indexOf(" ") === -1;
    };
    let validateSampleName = async (rule, value) => {
      if (value === "") {
        return Promise.reject("请输入样品名称");
      } else {
        if (!isValidStr(value)) {
          return Promise.reject("样品名称含有非法字符");
        }
        return Promise.resolve();
      }
    };

    let validateAlloyCode = async (rule, value) => {
      if (value === "") {
        return Promise.reject("请选择合金代码");
      }
    };

    return {
      ruleForm: {
        sample_name: '',
        alloy_code: '',
        sample_form: '',
        sample_shape: '',
        sample_length: '',
        sample_width: '',
        sample_thickness: '',
        sample_diameter: '',
        sample_col: '',
        sample_gloss: '',
        sample_roughness: '',
      },
      rules: {
        sample_name: [
          {
            validator: validateSampleName,
            trigger: "change",
            required: true,
            whitespace: true,
          },
       ],
        alloy_code:[
          {
            validator: validateAlloyCode,
            trigger: "change",
            required: true,
            whitespace: true,
          }
        ],
      },
      layout: {
        labelCol: { span: 4 },
        wrapperCol: { span: 14 },
      },
      submitting: false,
      alloyCodeSelectionOptions: [],
      headers: {
        authorization: 'authorization-text',
      },
    }
  },
  mounted() {
    this.fetch()
  },
  methods: {
    // 从后端获取数据
    fetch() {
      this.data =[]
      this.alloyCodeSelectionOptions = []
      this.axios
        .get('/attachment_management/alloy_phase_diagram/')
        .then((res) => {
          const data = res.data
          for (let i = 0; i < data.length; ++i) {
            this.alloyCodeSelectionOptions.push({
              url: data[i].url,
              label: data[i].alloy_code,
            })
          }
          // this.ruleForm.alloy_code = data.length === 0 ? '' : data[0].url
          if (this.url !== '') {
            this.axios
              .get(this.url)
              .then((res) => {
                const data = res.data
                this.ruleForm.sample_name = data.sample_name
                this.ruleForm.alloy_code = data.alloy_code
                this.ruleForm.sample_form  = data.sample_form
                this.ruleForm.sample_shape  = data.sample_shape
                this.ruleForm.sample_length  = data.sample_length
                this.ruleForm.sample_width = data.sample_width
                this.ruleForm.sample_thickness = data.sample_thickness
                this.ruleForm.sample_diameter = data.sample_diameter
                this.ruleForm.sample_col = data.sample_col
                this.ruleForm.sample_gloss = data.sample_gloss
                this.ruleForm.sample_roughness = data.sample_roughness
              })
              .catch((error) => {
                console.log('Error', error.message)
              })
          }
        })
        .catch((error) => {
          console.log('Error', error.message)
          this.ruleForm.alloy_code = ''
        })
    },
    handleFinish(values) {
      this.submitting = true

      const formData = new FormData()
      formData.append('sample_name', values.sample_name)
      formData.append('alloy_code', values.alloy_code)
      formData.append('sample_form', values.sample_form)
      formData.append('sample_shape', values.sample_shape)
      formData.append('sample_length', values.sample_length)
      formData.append('sample_width', values.sample_width)
      formData.append('sample_thickness', values.sample_thickness)
      formData.append('sample_diameter', values.sample_diameter)
      formData.append('sample_col', values.sample_col)
      formData.append('sample_gloss', values.sample_gloss)
      formData.append('sample_roughness', values.sample_roughness)

      if (this.url !== '') {
        this.axios
          .put(this.url, formData)
          .then(() => {
            this.submitting = false
            message.success('修改成功！')
            this.$emit('operate-success')
          })
          .catch((error) => {
            this.submitting = false
            message.error('修改失败！')
            this.$emit('operate-failed')
            console.log('Error', error.message)
          })
      } else {
        this.axios
          .post('/property_management/macro_organization/', formData)
          .then(() => {
            this.submitting = false
            message.success('添加成功！')
            this.$emit('operate-success')
          })
          .catch((error) => {
            this.submitting = false
            message.error('添加失败！')
            this.$emit('operate-failed')
            console.log('Error', error.message)
          })
      }
    },
  },
}
</script>
